package ae.pcfc.cldos.online.web.services.security.filters;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.web.tomcat.security.login.WebAuthentication;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.web.filter.GenericFilterBean;

import ae.pcfc.cldos.online.web.util.RequestUtils;

/**
 * Custom filter for remember me with JBOSS integration
 * 
 * @author arosa
 *
 */
public class RememberMeCustomFilter extends GenericFilterBean {

	private RememberMeServices rememberMeServices;
	
	public void setRememberMeServices(RememberMeServices rememberMeServices) {
		this.rememberMeServices = rememberMeServices;
	}
	
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
	    HttpServletResponse response = (HttpServletResponse) res;
	    
	    if(RequestUtils.isResourceRequest(request)){
	    	chain.doFilter(req, response);
	    	return;
	    }
	    
	    Principal principal = request.getUserPrincipal();
        if (principal == null) {
            Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
            if(rememberMeAuth!=null){
	            UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)rememberMeAuth;
	
	            String username = userToken.getName();
	            String password = (String) rememberMeAuth.getCredentials();
	            if(username!=null && !username.isEmpty() && password!=null && !password.isEmpty()){
		            WebAuthentication pwl = new WebAuthentication();
					if(pwl.login(username, password)){
						rememberMeServices.loginSuccess(request, response, userToken);
					} else {
						rememberMeServices.loginFail(request, response);
					}
	            }
            }
        }
        
        chain.doFilter(req, res);
        
	}
	
	
}
